import request from "@/utils/request";
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Sidebar, Button, Badge, Space, Popup, Notify, Dialog, PasswordInput } from 'react-vant';
import { useNavigate } from 'react-router-dom'
import OrderContent from "./Order/OrderContent";
import { ShoppingCartO, Delete } from '@react-vant/icons'
import { connect } from 'react-redux'
import CartLists from './order/CartLists'
import store from '@/store'
import OrderDetail from './order/OrderDetail'
import OrderPay from './order/OrderPay'


let Order = (props) => {
    // 设置购物车弹出层的显示与隐藏
    const [visible, setVisible] = useState(false)
    const [active, setActive] = useState(0);
    const { user } = props;
    const navigator = useNavigate();
    const { getData } = props;

    // 菜品分类
    const [Category, setCategory] = useState([]);

    // 获取菜品分类
    const getCategory = async () => {
        const { data } = await request.get('/category');
        setCategory(data.data)
        console.log(data);
    }

    //菜品分类商品 
    const [dishesList, setDishesList] = useState([]);

    // 获取菜品分类商品
    const getDishesList = async (category) => {
        const { data } = await request.get(`/menu/selCategory`, {
            params: {
                category
            }
        })
        setDishesList(data.data)
    }

    // 用户购物车信息
    const [cartList, setCartList] = useState([]);
    // 用户购物车数量
    const [cartTotal, setCartTotal] = useState(0);

    // 获取用户购物车信息
    const getCartList = async () => {
        let { data } = await request.get('/cart/list/' + user.username)
        if (data.code === 200) {
            setCartList(data.data);
            setCartTotal(data.total);
        }
    }

    // 计算用户购物车总价
    const cartPrice = useMemo(() => {
        let price = 0
        if (cartList.length != 0) {
            cartList.reduce((prev, item) => {
                if (item.sales_price) {
                    price = prev + item.qty * item.sales_price
                    return prev + item.qty * item.sales_price
                } else {
                    price = prev + item.qty * item.price
                    return prev + item.qty * item.price
                }
            }, 0)
        }
        return price.toFixed(2)
    })

    // 添加购物车
    const addData = async (dishes_id) => {
        const { data } = await request.post('/cart/addData', {
            username: user.username,
            dishes_id
        });
        getCartList();
    }

    // 修改购物车数量
    const subData = async (dishes_id, qty) => {
        if (qty == 1) {
            const { data } = await request.post('/cart/deleteData', {
                username: user.username,
                dishes_id,
            })
            if (data.code == 200) {
                Notify.show({ type: 'success', message: '商品已从已选商品中移除' })
            }
            getCartList();
        }
        else if (qty - 1 < 0) {
            Notify.show({ message: '不能再减了!!!' })
        }
        else if (qty > 1) {
            const { data } = await request.post('/cart/updateData', {
                username: user.username,
                dishes_id,
                qty: qty * 1 - 1
            })
            getCartList();

        }

        // 如果商品数量为1就直接将该商品移除购物车

        // getCartList();
    }

    useEffect(() => {
        getCategory();
        getDishesList('招牌');
        getCartList();
    }, [])

    const [dishesQty, setDishesQty] = useState([]);

    // 获取菜品已在购物车中的数量
    useEffect(() => {
        let qty = [];
        dishesList.forEach((item) => {
            let carthas = false;
            cartList.forEach((item1) => {
                if (item.dishes_id === item1.dishes_id) {
                    qty.push(item1.qty);
                    carthas = true;
                }
            })
            if (carthas == false) {
                qty.push(0);
            }
        })
        setDishesQty(qty)
    }, [dishesList, cartList])

    // 清空购物车
    const clearCart = async () => {
        const { data } = await request.post('/cart/clear', {
            username: user.username
        })
        Notify.show({ type: 'success', message: '已选商品已清空' })
        setVisible(false)
        getCartList();
    }

    // 设置商品详情弹出层的显示与隐藏
    const [detailVisible, setDetailVisible] = useState(false);

    const [dishes, setDishes] = useState({});
    // 获取单个商品详情
    const getDishes = async (dishes_id) => {
        const { data } = await request.get('/menu/selID', {
            params: {
                dishes_id
            }
        });

        if (data.code === 200) {
            setDishes(data.data)
        }
    }


    const [dishQty, setDishQty] = useState(0);

    // 获取单个菜品已在购物车中的数量
    const getDishQty = (dishes_id) => {
        const data = cartList.find((item) => {
            return item.dishes_id == dishes_id
        })
        if (data) {
            setDishQty(data.qty);
        } else {
            setDishQty(0);
        }
    }

    // 设置结算页显示与隐藏
    const [payVisible, setPayVisible] = useState(false);

    // 添加订单
    const addOrder = async () => {
        let date = (new Date()).toLocaleDateString().replace(/\//g, '-');

        const { data } = await request.post('/order/addData', {
            username: user.username,
            complete_time: date,
            telphone: user.telphone,
            dishes: JSON.stringify(cartList),
            complete: 1,
            count_price: cartPrice
        })
        getData();
        console.log(data);
    }
    const [pwd, setPwd] = useState('');

    const infoRef = useRef();

    useEffect(() => {
        infoRef.current = pwd;
    }, [pwd]);

    // 检测用户是否支付
    // const checkPay = async () => {
    //     console.log(PatPwdcheck);
    //     if (PatPwdcheck) {
    //         Notify.show({ type: 'success', message: '支付成功' });
    //         addOrder();
    //         clearCart();
    //         getCartList();
    //         setPayVisible(false);
    //     } else if (paypwd.length < 6) {
    //         setPayVisible(true);
    //         Notify.show({ type: 'danger', message: '支付密码格式不正确' });
    //     }
    // }
    const checkPay = async () => {

        const { data } = await request.post('/user/isPay', {
            uid: user.uid,
            paypassword: infoRef.current
        })
        if (data.code === 200) {
            Notify.show({ type: 'success', message: '支付成功' });
            addOrder();
            clearCart();
            getCartList();
            setPayVisible(false);
        }
        else if (data.code === 400) {
            Notify.show({ type: 'danger', message: '支付密码错误' })
            setPwd('');
        }
    }
    return (
        <div style={{ height: '70vh', overFlow: 'auto' }}>
            <Sidebar
                value={active}
                onChange={(v) => {
                    setActive(v);
                }}
                style={{ height: '57vh' }}
            >
                {
                    Category.map((item) => {
                        return (
                            <Sidebar.Item
                                contentStyle={{ backgroundColor: 'white', padding: '10px 10px', overflowY: 'auto' }}
                                title={item.category}
                                key={item.id}
                                onClick={getDishesList.bind(null, item.category)}
                            >
                                <OrderContent
                                    addData={addData}
                                    dishesList={dishesList}
                                    cartList={cartList}
                                    dishesQty={dishesQty}
                                    subData={subData}
                                    getDishes={getDishes}
                                    setDetailVisible={setDetailVisible}
                                    getDishQty={getDishQty}
                                >

                                </OrderContent>
                            </Sidebar.Item>
                        )
                    })
                }
            </Sidebar>
            <div className="submitOrder">
                <Badge content={cartTotal}>
                    <ShoppingCartO
                        color="#bbb"
                        fontSize={'35px'}
                        onClick={() => { setVisible(true) }}
                    />
                </Badge>
                <Space>
                    <span className="price">{cartPrice}</span>
                    <Button type='danger' round onClick={() => {
                        if (user.paypassword == null) {
                            Dialog.alert({
                                theme: 'round-button',
                                showCancelButton: true,
                                message: (
                                    <div style={{ textAlign: 'center', margin: '16px' }}>
                                        您还未设置支付密码,请先在下方输入支付密码
                                        <PasswordInput onSubmit={(val) => {
                                            store.dispatch({ type: 'setpaypwd', payload: { paypassword: val } })
                                            const { data } = request.post('/user/payPassword', {
                                                uid: user.uid,
                                                paypassword: val
                                            })
                                        }} />
                                    </div>
                                )
                            })
                        } else if (cartList.length != 0) {
                            setPayVisible(true)
                        } else {
                            Notify.show({ type: 'danger', message: '您还未选菜品喔' })
                        }
                    }}>提交订单</Button>
                </Space>
            </div>
            <Popup
                visible={visible}
                closeable
                style={{ height: '50%' }}
                position='bottom'
                round
                title='已选商品'
                closeIcon={<Delete />}
                onClickCloseIcon={() => {
                    Dialog.alert({
                        theme: 'round-button',
                        showCancelButton: true,
                        message: '确认清空商品吗?',
                        onConfirm: clearCart
                    })

                }}
                onClickOverlay={() => setVisible(false)}
            >
                <CartLists
                    addData={addData}
                    getCartList={getCartList}
                    cartList={cartList}
                    dishesQty={dishesQty}
                    subData={subData}
                    getDishes={getDishes}
                    setDetailVisible={setDetailVisible}
                >
                </CartLists>
                <div className="submitShop">
                    <Space>
                        <span className="price">{cartPrice}</span>
                        <Button type='danger' size="small" round onClick={() => {
                            if (user.paypassword == null) {
                                Dialog.alert({
                                    theme: 'round-button',
                                    showCancelButton: true,
                                    message: (
                                        <div style={{ textAlign: 'center', margin: '16px' }}>
                                            您还未设置支付密码,请先在下方输入支付密码
                                            <PasswordInput onSubmit={(val) => {
                                                const { data } = request.post('/user/payPassword', {
                                                    uid: user.uid,
                                                    paypassword: val
                                                })
                                                store.dispatch({ type: 'setpaypwd', payload: { paypassword: val } })
                                            }} />
                                        </div>
                                    )
                                })
                            } else if (cartList.length != 0) {
                                // setVisible(false);
                                setPayVisible(true)
                            } else {
                                Notify.show({ type: 'danger', message: '您还未选菜品喔' })
                            }
                        }}>提交订单</Button>
                    </Space>
                </div>
            </Popup >
            <Popup
                visible={detailVisible}
                closeable
                style={{ height: '70%' }}
                position='bottom'
                round
                title='商品详情'
                onClose={() => setDetailVisible(false)}
            >
                <OrderDetail
                    dishes={dishes}
                >
                </OrderDetail>
            </Popup>
            <Popup
                visible={payVisible}
                closeable
                style={{ height: '70%' }}
                position='bottom'
                round
                title='商品结算'
                onClose={() => setPayVisible(false)}
            >
                <OrderPay cartList={cartList} cartPrice={cartPrice}></OrderPay>
                <div className="submitShop">
                    <Space>
                        <span className="price">{cartPrice}</span>
                        <Button type='danger' round size='small' onClick={() => {
                            Dialog.alert({
                                theme: 'round-button',
                                showCancelButton: true,
                                message: (
                                    <div style={{ textAlign: 'center', margin: '16px' }}>
                                        请输入支付密码
                                        <PasswordInput onChange={(val) => {
                                            setPwd(val)
                                        }}
                                        />
                                    </div>
                                ),
                                onConfirm: checkPay,
                                onCancel: () => {
                                    Notify.show({ type: 'danger', message: '取消支付' })
                                }
                            })
                        }}>
                            提交订单
                        </Button>
                    </Space>
                </div>
            </Popup>
        </div >
    )
}

const mapStateToProps = function (state) {
    return {
        user: state.userInfo
    }
}
Order = connect(mapStateToProps)(Order)
export default Order;